import { defineComponent, reactive, toRefs, computed, onMounted, watch } from "vue"
import { inject } from "vue"
import {是浏览器环境否} from 'amtf/utils';

import { HOOKS_NAME } from "../util/constant"

import { useEmitter } from "amtf/hooks"
import emitter from "amtf/utils/emitter"
import { use样式 } from "amtf/hooks"
import {
    isNumber,
    getViewportOffset,
    getMousePosition,
    getValByUnit,
    拼组件名,
    isFunction,
    isBoolean,
    getRandomId,
} from "amtf/utils"
const 主名 = "table-column-resizer"
const 组件名 = 拼组件名(主名)

export default defineComponent({
    name: 组件名,
    props: {
        parentRendered: {
            type: Boolean,
            required: true,
        },
        tableContainerEl: {
            type: 是浏览器环境否 ? HTMLDivElement : Object,

            default: null,
        },
        hooks: {
            type: Object,
            required: true,
        },
        colgroups: {
            type: Array,
            required: true,
        },
        isColumnResizerHover: {
            type: Boolean,
            required: true,
        },
        isColumnResizing: {
            type: Boolean,
            required: true,
        },
        setIsColumnResizerHover: {
            type: Function,
            required: true,
        },
        setIsColumnResizing: {
            type: Function,
            required: true,
        },
        setColumnWidth: {
            type: Function,
            required: true,
        },
        columnWidthResizeOption: {
            type: Object,
            default: function () {
                return null
            },
        },
    },
    setup(props) {
        // console.log(`列拖动组件 ing👇`)
        const { 拼样式名_table直属 } = use样式(主名)

        const state = reactive({
            columnResizerStartX: 0,
            currentResizingColumn: null,
            columnResizerHandlerWidth: 5,
            columnResizerRect: {
                top: 0,
                left: 0,
                height: 0,
            },
        })

        const columnMinWidth = computed(() => {
            let result = 30
            if (props.columnWidthResizeOption) {
                const { minWidth } = props.columnWidthResizeOption
                if (isNumber(minWidth) && minWidth > 0) {
                    result = minWidth
                }
            }
            return result
        })

        watch(
            () => props.parentRendered,
            val => {
                // console.log(`column-resizer props.parentRendered变化了 👉`, val)
                if (val) {
                    // header cell mousemove
                    // console.log(`props.hooks 👉`, props.hooks)
                    props.hooks.addHook(HOOKS_NAME.HEADER_CELL_MOUSEMOVE, ({ event, column }) => {
                        // console.log(`column 👉`, column)
                        if (column.disableResizing) return
                        initColumnResizerPosition({ event, column })
                    })
                }
            },
            { immediate: true }
        )

        function initColumnResizerPosition({ event, column }) {
            // console.log(`initColumnResizerPosition 👉`, column)
            const { tableContainerEl, isColumnResizing } = props
            if (tableContainerEl && !isColumnResizing) {
                // console.log(
                //   `tableContainerEl.getBoundingClientRect() 👉`,
                //   tableContainerEl.getBoundingClientRect()
                // )
                const { left: tableContainerLeft, top: tableContainerTop } = tableContainerEl.getBoundingClientRect()
                const col = props.colgroups.find(x => x.key === column.key)
                // 表头分组，不支持分组表头列宽拖动
                if (!col) {
                    return false
                }
                if (col._realTimeWidth) {
                    // console.log(`col 👉`, col)
                    const target = event.target
                    const cellRect = target.getBoundingClientRect()
                    const { height, left, top } = cellRect
                    state.columnResizerRect.left = left + col._realTimeWidth - tableContainerLeft
                    state.columnResizerRect.top = top - tableContainerTop
                    state.columnResizerRect.height = height
                    state.currentResizingColumn = col
                    state.columnResizerStartX = left + col._realTimeWidth
                } else {
                    console.warn("Resizer column needs set column width")
                }
            }
        }

        function setColumnResizerPositionByDrag(event) {
            // console.log(
            //   `setColumnResizerPositionByDrag 👉`,
            //   setColumnResizerPositionByDrag
            // )
            const { currentResizingColumn } = state
            if (props.tableContainerEl && props.isColumnResizing) {
                const { left: tableContainerLeft } = props.tableContainerEl.getBoundingClientRect()
                if (props.isColumnResizing && currentResizingColumn) {
                    const { columnResizerStartX } = state
                    // 不允许拖动小于列最小宽度
                    if (
                        currentResizingColumn._realTimeWidth + (event.clientX - columnResizerStartX) >
                        columnMinWidth.value
                    ) {
                        state.columnResizerRect.left = event.clientX - tableContainerLeft
                    }
                }
            }
        }

        function columnResizerHandlerMousedown({ event }) {
            // console.log(
            //   `columnResizerHandlerMousedown props.isColumnResizerHover 👉`,
            //   props.isColumnResizerHover
            // )
            if (props.isColumnResizerHover) {
                // console.log(` props.setIsColumnResizing 👉`, props.setIsColumnResizing)
                props.setIsColumnResizing(true)
                // add document mousemove listener
                document.addEventListener("mousemove", setColumnResizerPositionByDrag)
                // add document mouseup listener
                document.addEventListener("mouseup", columnResizerMouseup)
                // stop text select when reszing
                document.onselectstart = function () {
                    return false
                }
                document.ondragstart = function () {
                    return false
                }
            }
        }

        function columnResizerMouseup(event) {
            const { currentResizingColumn, columnResizerStartX } = state
            if (!props.isColumnResizing || !currentResizingColumn) {
                return false
            }
            let differWidth
            // 拖动小于列最小宽度
            if (currentResizingColumn._realTimeWidth + (event.clientX - columnResizerStartX) < columnMinWidth.value) {
                differWidth = columnMinWidth.value - currentResizingColumn._realTimeWidth
            } else {
                differWidth = event.clientX - columnResizerStartX
            }
            differWidth = Math.floor(differWidth)
            // console.log(`differWidth 👉`, differWidth)
            // 偏差阈值，低于则不处理
            if (Math.abs(differWidth) > 1) {
                let nextColumnWidth = currentResizingColumn._realTimeWidth
                nextColumnWidth += differWidth
                // set column width
                // console.log(`nextColumnWidth 👉`, nextColumnWidth)
                props.setColumnWidth({
                    colKey: currentResizingColumn.key,
                    width: nextColumnWidth,
                })
                if (props.columnWidthResizeOption) {
                    const { sizeChange } = props.columnWidthResizeOption
                    sizeChange &&
                        sizeChange({
                            column: currentResizingColumn,
                            differWidth,
                            columnWidth: nextColumnWidth,
                        })
                }
            }
            clearColumnResizerStatus()
            // add document mousemove listener
            document.removeEventListener("mousemove", setColumnResizerPositionByDrag)
            // add document mouseup listener
            document.removeEventListener("mouseup", columnResizerMouseup)
        }

        function clearColumnResizerStatus() {
            state.currentResizingColumn = null
            state.columnResizerStartX = 0
            props.setIsColumnResizerHover(false)
            props.setIsColumnResizing(false)
            // enable text select when reszing
            document.onselectstart = function () {
                return true
            }
            document.ondragstart = function () {
                return true
            }
        }

        return () => (
            <div class={拼样式名_table直属("column-resizer")}>
                <div
                    class={[
                        拼样式名_table直属("column-resizer-handler"),
                        props.isColumnResizerHover || props.isColumnResizing ? "active" : "",
                    ]}
                    style={{
                        left: state.columnResizerRect.left - state.columnResizerHandlerWidth + "px",
                        top: state.columnResizerRect.top + "px",
                        height: state.columnResizerRect.height + "px",
                    }}
                    onClick={() => {}}
                    onMousedown={event => columnResizerHandlerMousedown({ event })}
                    onMouseenter={() => {
                        // console.log(`column-resizer onMouseenter ing👇`)
                        return props.setIsColumnResizerHover(true)
                    }}
                    onMouseleave={() => props.setIsColumnResizerHover(false)}
                    onMouseup={event => columnResizerMouseup(event)}
                />
                <div
                    class={拼样式名_table直属("column-resizer-line")}
                    style={{
                        display: props.isColumnResizing ? 'block' : 'none',
                        // display: "block",
                        left: state.columnResizerRect.left + "px",
                    }}
                />
                {/* {`state.columnResizerRect.left=${state.columnResizerRect.left}`} */}
            </div>
        )
    },
})
